package com.yonyou.pmclouds.uspace.util;

import com.yonyou.pmclouds.basecom.conf.USpaceProperties;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.util.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class USpaceUtil {

    public static final String SIGN_KEY = "sign";

    /**
     * 构建友空间服务的 请求路径
     * @param uri
     * @param uspaceProperties
     * @param parameters
     * @return
     * @throws BusinessException
     */
    public static String buildGetUrl(String uri, USpaceProperties uspaceProperties, Map<String, String> parameters) throws BusinessException {

        StringBuilder url = new StringBuilder(uspaceProperties.getInApiHost());
        url.append(uri).append("?");

        if (!CollectionUtils.isEmpty(parameters)) {
            Iterator<String> iter = parameters.keySet().iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                String value = parameters.get(key);
                url.append(key).append("=").append(value).append("&");
            }
        }

        String sign = USpaceUtil.buildSign(uri, parameters,uspaceProperties.getSalt());
        url.append(SIGN_KEY).append("=").append(sign);
        return url.toString();
    }


    /**
     * 约定签名
     * 签名，算法为：sign = md5(URI+STR+SALT)
     * URI: /user/recently/1;
     * STR: 参数数组按键由小到大排序（除去sign字段），然后拼装成http query形式：如上面的STR为：timestamp=1470664390&token=8e7fc32a64d3d16fee1d49ebc8c97115&v=v1.0;
     * SALT: 固定盐，由友空间颁发；
     *
     * @param path, parameters
     * @return java.lang.String
     */
    public static String buildSign(String path, Map<String, String> parameters, String salt) throws BusinessException {

        Map<String, String> sortMap = new TreeMap<>();
        if (!CollectionUtils.isEmpty(parameters)) {
            sortMap.putAll(parameters);
        }
        StringBuilder signStr = new StringBuilder(path);
        Iterator<String> iter = sortMap.keySet().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            String value = sortMap.get(key);
            try {
                value = URLDecoder.decode(value, "utf-8");
            } catch (UnsupportedEncodingException e) {
                throw new BusinessException("转码失败!",e);
            }
            signStr.append(key).append("=").append(value).append("&");
        }
        signStr.deleteCharAt(signStr.length() - 1);
        signStr.append(salt);
        return DigestUtils.md5Hex(signStr.toString());
    }
}
